import { defineComponent, type PropType } from "vue";
// import type { MenuItem } from "./types";
// import { toLine } from "@/utils";
import * as Icons from "@element-plus/icons-vue";
import "./index.scss";
// 菜单组件
export default defineComponent({
  name: "Menu",
  props: {
    // 菜单数据
    data: {
      type: Array as PropType<any[]>,
      default: () => [],
      required: true,
    },
    // 是否折叠菜单
    collapse: {
      type: Boolean,
      default: false,
    },
    // 默认选中项
    defaultActive: {
      type: String,
      default: "",
    },
    // 是否使用路由模式
    router: {
      type: Boolean,
      default: false,
    },

    // 菜单名称 键名
    name: {
      type: String,
      default: "name",
    },
    // 菜单索引 键名
    index: {
      type: String,
      default: "index",
    },
    // 菜单图标 键名
    icon: {
      type: String,
      default: "icon",
    },
    // 子菜单 键名
    children: {
      type: String,
      default: "children",
    },
  },
  // jsx 做的的递归组件
  // 如果是模版做递归呢？
  setup(props) {
    let renderMenu = (data: any[]) => {
      return data.map((item: any) => {
        // 处理菜单的图标
        // item.i = `el-icon-${toLine(item.icon)}`;
        item.i = (Icons as any)[item[props.icon!]]; //这个感叹号表示非空断言，告诉ts编译器item.icon一定有值
        // 定义el-sub-menu插槽内容
        let slots = {
          title: () => {
            return (
              <>
                <item.i class="mr" />
                <span>{item[props.name!]}</span>
              </>
            );
          },
        };
        // 递归渲染子菜单children
        if (item[props.children!] && item[props.children!].length > 0) {
          return (
            <el-sub-menu index={item[props.index!]} v-slots={slots}>
              {renderMenu(item[props.children!])}
            </el-sub-menu>
          );
        }
        // 渲染普通菜单项
        return (
          <el-menu-item index={item[props.index!]}>
            <item.i class="mr" />
            <span>{item[props.name!]}</span>
          </el-menu-item>
        );
      });
    };
    return () => {
      return (
        <el-menu
          class="menu"
          collapse={props.collapse}
          default-active={props.defaultActive}
          router={props.router}
        >
          {renderMenu(props.data)}
        </el-menu>
      );
    };
  },
});
